package com.mini6410.ADC;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

import com.friendlyarm.AndroidSDK.HardwareControler;
import com.mini6410.R;

/**
 * 
 * ClassName:ADCActivity
 * Reason:	 ADC Demo
 *
 * @author   snowdream
 * @version  
 * @since    Ver 1.1
 * @Date	 2011	2012-03-16		12:04
 *
 * @see 	 
 */
public class ADCActivity extends Activity {
	private static final String TAG = "ADCActivity";
	
	/*刷新UI标记*/
	public static final int Update_UI = 0;

	/*计时器*/
	private Timer mTimer = null;
	private TimerTask mTimerTask = null;
	
	/*用来显示ADC返回值的控件*/
	private TextView mTextView_ADC = null;

	/*读取ADC的返回值*/
	private int result = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.adcdemo);

		initUI();
		initData();
	}

	/**
	 * 
	 * initUI: 初始化UI
	 *
	 * @param   
	 * @return     
	 * @throws 
	 */
	private void initUI() {
		mTextView_ADC = (TextView)findViewById(R.id.TextView_adcresult);
	}

	/**
	 * 
	 * initData: 新建定时器，每隔500ms发出消息，通知Activity刷新UI一次。
	 *
	 * @param   
	 * @return     
	 * @throws 
	 */
	private void initData() {
		mTimer = new Timer();
		mTimerTask = new TimerTask() {
			@Override
			public void run() {
				
				/*调用底层库API读取ADC的值，正常情况下，返回ADC值，否则，出错，返回-1*/
				result = HardwareControler.readADC();
				
				if(-1 == result){
					Log.e(TAG,"Read ADC Error!");
				}else{
					Log.i(TAG,"readADC result: "+ result);
					mHandler.sendMessage(mHandler.obtainMessage(Update_UI));
				}
			}
		};
		mTimer.schedule(mTimerTask, 0, 500);
	}

	private Handler mHandler  = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			int type = msg.what;
			switch (type) {
			case Update_UI:
				mTextView_ADC.setText(String.valueOf(result));
				break;
			default:
				break;
			}
		}

	};

	@Override
	protected void onDestroy() {
		if(mTimer != null){
			mTimer.cancel();
			mTimer = null;
		}
		super.onDestroy();
	}


}
